package com.hzchendou.blog.demo.resource.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

/**
 * 角色服务
 *
 * @Date: 2022-05-25 11:57
 * @since: 1.0
 */
@Service
public class RoleService {

    public List<ConfigAttribute> roles = new ArrayList<>();

    private Map<String, List<ConfigAttribute>> urlRoleMaps = new HashMap<>();

    @PostConstruct
    public void init() {
        roles.addAll(SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN", "ROLE_VIP"));
        urlRoleMaps.put("/", SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN"));
        urlRoleMaps.put("/user/hello", SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN"));
        urlRoleMaps.put("/user/nickname", SecurityConfig.createList("ROLE_VIP"));
        urlRoleMaps.put("/admin/hello", SecurityConfig.createList("ROLE_ADMIN"));
    }

    /**
     * 获取所有角色信息
     *
     * @return
     */
    public Collection<ConfigAttribute> getAllRoles() {
        return Collections.unmodifiableList(roles);
    }

    /**
     * 依据请求路径查询所需权限
     *
     * @param path
     * @return
     */
    public Collection<ConfigAttribute> getRoleByPath(String path) {
        Collection<ConfigAttribute> roles = urlRoleMaps.get(path);
        if (roles == null) {
            return Collections.EMPTY_LIST;
        }
        return Collections.unmodifiableCollection(roles);
    }

}
